<template>
  <el-form label-width="100px">
    <el-form-item label="SPU 名称"> SPU 名称 </el-form-item>
    <el-form-item label="SKU 名称">
      <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input type="number" v-model="skuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input type="number" v-model="skuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" placeholder="规格描述" rows="4" v-model="skuInfo.skuDesc"></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item
          v-for="attr in attrList"
          :key="attr.id"
          :label="attr.attrName"
        >
          <el-select placeholder="请选择" v-model="attr.attrIdValueId">
            <el-option
              :value="`${item.attrId}:${item.id}`"
              v-for="item in attr.attrValueList"
              :key="item.id"
              :label="item.valueName"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item
          :label="attr.saleAttrName"
          v-for="attr in saleAttrList"
          :key="attr.id"
        >
          <el-select placeholder="请选择" v-model="attr.attrIdAttrValueId">
            <el-option
              v-for="item in attr.spuSaleAttrValueList"
              :key="item.id"
              :label="item.saleAttrValueName"
              :value="`${item.baseSaleAttrId}:${item.id}`"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="图片列表">
      <el-table
        border
        stripe
        :data="spuImgList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img :src="row.imgUrl" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tag v-if="row.isDefault === '1'">默认图片</el-tag>
            <el-button type="primary" v-else @click="changeDefault(row)"
              >设为默认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="default" @click="emit('setState', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import type { SkuAttrValueListType,
   SkuInfoItemType, 
    SkuImageListType,  
     SkuSaleAttrValueListType,} from "@/api/sku";

export default defineComponent({
  name: "SkuForm",
});
</script>

<script setup lang="ts">
  import { onMounted, ref } from "vue";
import { requestSpuImgList,requestSpuSaleAttrList} from "@/api/spu";
import type {SpuSaleAttrListType,SpuImgListType,SpuInfoType,SpuImgItemType} from "@/api/spu";
import { requestSaveSkuInfo } from "@/api/sku";
import { storeToRefs } from "pinia";
import useAttrStore from "@/stores/attr";
import {requestAttrList} from "@/api/attr";
import type{attrListType} from "@/api/attr";
import { ElMessage } from "element-plus";

//初始化收集数据
const skuInfo = ref<SkuInfoItemType>({
  //需要我们直接进行双向绑定收集的
  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",

  //需要从props中的spu中直接拿
  spuId:0,
  tmId:0,
  category3Id:0,

  //需要计算收集的
  skuDefaultImg:"",

  //需要计算收集的
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});

//1.接受props传值
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();
const spuInfo = props.spuInfo;

//2.接受自定义事件,用来切换组件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();

//3.拿到pinia中的三级分类数据
const attrStore = useAttrStore();
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

/* //获取所有的平台属性
requestAttrList(1id,2id,3id)==>attrListType
//获取所有销售属性
requestBaseSaleAttrList()===>BaseSaleAttrListType
//根据当前的spuId获取所有图片列表
requestSpuImgList(spuId)===>SpuImgListType */


//4.初始化一些值 保存初始化请求的数据
const attrList = ref<attrListType>([]);//平台属性列表
const saleAttrList= ref<SpuSaleAttrListType>([]);
const spuImgList =ref <SpuImgListType>([]);
const getInitData = async () => {
  const promise1 = requestAttrList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number,
  );
  const promise2 = requestSpuSaleAttrList(spuInfo.id as number);
  const promise3 = requestSpuImgList(spuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);
  attrList.value = result[0];
  saleAttrList.value = result[1];
  spuImgList.value = result[2];
};

onMounted(() =>{
  //发送初始化请求
  getInitData();
});

//5.收集我们选中的平台属性
/* 
  收集的时候只需要某些下拉菜单的
  attrId?: number;//就是平台属性具体某一个下拉数据的attrId
  valueId?: number;//就是平台属性具体某一个下拉数据的id
  //下边都是不需要的
  id?: number;
  skuId?: number;
  attrName?: string;
  valueName?: string;
*/

// 6.收集选中的销售属性
/* 
  收集需要的数据是:
  saleAttrValueId?: number;
  saleAttrId?: number;

  //不需要
  id?: number;
  skuId?: number;
  spuId?: number;
  saleAttrName?: string;
  saleAttrValueName?: string;
*/

interface ImgListType {
  id:number;
  imgName:string;
  imgUrl:string;
  spuId:number;
}

// 定义一个数据，收集选中的图片组成的数据（千万不要修改原来的数组）
  const skuImgList = ref<SpuImgListType>([]);
  const handleSelectionChange = (val:ImgListType[])=>{
    console.log(val);
      // spuImgList.value = val;
  //val的收集就是从spuImgList中收集的,所以收集过来的值类型和我们的类型一模一样,直接赋值收集即可
  skuImgList.value = val;
};

//设置默认图片按钮
const changeDefault = (row:SpuImgItemType) =>{
  //使用排他把全部的isDefault设置false
  spuImgList.value.forEach((item) =>{
    item.isDefault = "0";
  });
  //给当前的设置和true
  row.isDefault = "1";
};

// 提交
const save=async () =>{
  //1. 把props传递过来的spuInfo的某些数据收集在skuInfo中
  skuInfo.value.spuId = props.spuInfo.id;
  skuInfo.value.tmId = props.spuInfo.tmId as number;
  skuInfo.value.category3Id = props.spuInfo.category3Id;

  //2. 收集当前组件中其他数据
  //收集平台属性
  attrList.value.forEach((item) => {
    if (item.attrIdValueId) {
      const [attrId, valueId] = item.attrIdValueId.split(":");
      const newAttrObj = {
        attrId: +attrId,
        valueId: +valueId,
      };
      (skuInfo.value.skuAttrValueList as SkuAttrValueListType).push(newAttrObj);
    }
  });

  // 收集销售属性
  saleAttrList.value.forEach((item)=>{
    if(item.attrIdAttrValueId) {
      const [saleAttrId,saleAttrValueId] = item.attrIdAttrValueId.split(":");
      const newSaleAttrObj = {
      //拼接
        saleAttrId:+ saleAttrId,
        saleAttrValueId: + saleAttrValueId,
      };
      (skuInfo.value.skuSaleAttrValueList as SkuSaleAttrValueListType).push(
        newSaleAttrObj
      );
    }
  });

  //收集图片数据
  skuImgList.value.forEach((item)=> {
        /*
      需要收集的值

        imgName: string;
        imgUrl: string;
        spuImgId?: number;
        isDefault?: string;

        //不需要
        id?: number;
        skuId?: number;

    */
   const newSkuImg = {
    imgName:item.imgName,
    imgUrl:item.imgUrl,
    spuImgId:item.id,
    isDefault:item.isDefault,
   };

   if(item.isDefault === "1") {
    skuInfo.value.skuDefaultImg = item.imgUrl;
   }
   
   (skuInfo.value.skuImageList as SkuImageListType).push(newSkuImg);
  });

  // 发送请求
  try {
    await requestSaveSkuInfo(skuInfo.value);
    ElMessage.success("新增sku成功");
    emit("setState",0);
  }catch (e) {
    ElMessage.error("新增sku失败");
  }
};
</script>
